using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using BizTown;
using System.IO;
using Neo.Core;
using Neo.SqlClient;
using System.Drawing;

public partial class admin_actions_clear_student_data : BiztownCustomPage
{
    ObjectContext neoContext = new ObjectContext(DataHelper.GetDataStore());

    protected void Page_Init(object sender, EventArgs e)
    {

        L_MessageOutput.Style.Add("line-height", "1.6em");
    }


    protected void ClearStudentData(object sender, EventArgs e)
    {
        try
        {
            ResetStudentAccounts();
            ResetBusinessLoanApprovals();
            RemoveDeposits();
            RemoveSurveyBallots();
            RemovePayments();
            RemoveWorkOrders();
            RemoveMessages();
            RemoveInvoices();
            RemoveBusinessDirectoryEntries();
            RemoveNewspaper();
            RemoveSavedBookmarks();
            RemoveWebPages();
            RemoveSigns();
            ResetAutoSavings();
            ResetPaycheckDirectDeposit();
            DeleteMediaCenterFiles();
            B_ClearStudentData.Visible = false;
            HtmlSpan_InformationText.Visible = false;
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "Error: An unhandled error occurred while attempting to clear student data.", exception);
        }
    }

    private void ResetStudentAccounts()
    {
        try
        {
            StudentList studentList = new StudentFactory(neoContext).FindAllObjects();
            foreach (Student student in studentList)
            {
                if (student.StudentId < 979)
                {
                    student.FirstName = "";
                    student.LastName = "";
                    student.Photo = "";
                }
            }
            neoContext.SaveChanges();
            DataHelper.RunSqlStatement("update Students set BusinessJobId=null, PortfolioId=null Where StudentId < 979");
            L_MessageOutput.Text += "<span class='success'>Reset student accounts successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to reset student accounts.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to reset student accounts.</span><br>";
        }
    }
    
    private void ResetBusinessLoanApprovals()
    {
        try
        {
            DataHelper.RunSqlStatement("UPDATE Businesses SET StartingBalance = null, IsLoanApproved = 0, OfficeLength=null, OfficeWidth=null");
            L_MessageOutput.Text += "<span class='success'>Reset business loans and office space successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to reset business loans and/or office space.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to reset business loans and/or office space.</span><br>";
        }
    }

    /// <summary>
    /// Removes both BusinessDeposits and PersonalCheckingDeposits
    /// </summary>
    private void RemoveDeposits()
    {
        try
        {
            // first, remove BusinessDeposit entries
            BusinessDepositList businessDepositList = new BusinessDepositFactory(neoContext).FindAllObjects();
            foreach (BusinessDeposit businessDeposit in businessDepositList)
            {
                businessDeposit.Delete();
            }
            neoContext.SaveChanges();
            // now, remove PersonalCheckingDeposit entries
            PersonalCheckingDepositList personalCheckingDepositList = new PersonalCheckingDepositFactory(neoContext).FindAllObjects();
            foreach (PersonalCheckingDeposit personalCheckingDeposit in personalCheckingDepositList)
            {
                personalCheckingDeposit.Delete();
            }
            neoContext.SaveChanges();
            L_MessageOutput.Text += "<span class='success'>Removed deposits successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to remove deposits.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to remove deposits.</span><br>";
        }
    }
    
    /// <summary>
    /// Removes both the BallotQuestions (the 6 questions selected by the business) selected and the choices selected by the students (StudentBallotSelections)
    /// </summary>
    private void RemoveSurveyBallots()
    {
        try
        {
            // First, remove StudentBallotSelection entries
            StudentBallotSelectionList studentBallotSelectionList = new StudentBallotSelectionFactory(neoContext).FindAllObjects();
            foreach (StudentBallotSelection studentBallotSelection in studentBallotSelectionList)
            {
                studentBallotSelection.Delete();
            }
            neoContext.SaveChanges();
            // now remove BallotQuestions
            BallotQuestionList ballotQuestionList = new BallotQuestionFactory(neoContext).FindAllObjects();
            foreach (BallotQuestion ballotQuestion in ballotQuestionList)
            {
                ballotQuestion.Delete();
            }
            neoContext.SaveChanges();
            L_MessageOutput.Text += "<span class='success'>Removed voting ballots successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to remove voting ballots.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to remove voting ballots.</span><br>";
        }
    }

    /// <summary>
    ///  Removes both BusinessPayments and POSPayments
    /// </summary>
    private void RemovePayments()
    {
        try
        {
            // first, remove BusinessPayments
            BusinessPaymentList businessPaymentList = new BusinessPaymentFactory(neoContext).FindAllObjects();
            foreach (BusinessPayment businessPayment in businessPaymentList)
            {
                businessPayment.Delete();
            }
            neoContext.SaveChanges();
            // now remove POS Payments
            POSPaymentList posPaymentList = new POSPaymentFactory(neoContext).FindAllObjects();
            foreach (POSPayment posPayment in posPaymentList)
            {
                posPayment.Delete();
            }
            neoContext.SaveChanges();
            L_MessageOutput.Text += "<span class='success'>Removed payments successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to remove payments.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to remove payments.</span><br>";
        }
    }

    /// <summary>
    /// Removes both WorkOrderItems and WorkOrders
    /// </summary>
    private void RemoveWorkOrders()
    {
        try
        {
            // first, remove the WorkOrderItem entries
            WorkOrderItemList workOrderItemList = new WorkOrderItemFactory(neoContext).FindAllObjects();
            foreach (WorkOrderItem workOrderItem in workOrderItemList)
            {
                workOrderItem.Delete();
            }
            neoContext.SaveChanges();
            // now, remove the WorkOrder entries
            WorkOrderList workOrderList = new WorkOrderFactory(neoContext).FindAllObjects();
            foreach (WorkOrder workOrder in workOrderList)
            {
                workOrder.Delete();
            }
            neoContext.SaveChanges();
            L_MessageOutput.Text += "<span class='success'>Removed work orders successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to remove work orders.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to remove work orders.</span><br>";
        }
    }

    /// <summary>
    /// Removes Message entries
    /// </summary>
    private void RemoveMessages()
    {
        try
        {
            // first, remove the Message entries
            MessageList messageList = new MessageFactory(neoContext).FindAllObjects();
            foreach (Message message in messageList)
            {
                message.Delete();
            }
            neoContext.SaveChanges();
            L_MessageOutput.Text += "<span class='success'>Removed messages successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to remove messages.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to remove messages.</span><br>";
        }
    }

    /// <summary>
    /// Removes both Invoice entries and InvoiceItem entries
    /// </summary>
    private void RemoveInvoices() 
    {
        try
        {
            // first, remove the InvoiceItem entries
            InvoiceItemList invoiceItemList = new InvoiceItemFactory(neoContext).FindAllObjects();
            foreach (InvoiceItem invoiceItem in invoiceItemList)
            {
                invoiceItem.Delete();
            }
            neoContext.SaveChanges();
            // now, remove the Invoice entries
            InvoiceList invoiceList = new InvoiceFactory(neoContext).FindAllObjects();
            foreach (Invoice invoice in invoiceList)
            {
                invoice.Delete();
            }
            neoContext.SaveChanges();
            L_MessageOutput.Text += "<span class='success'>Removed invoices successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to remove invoices.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to remove invoices.</span><br>";
        }
    }

    /// <summary>
    /// Clears the BusinessDirectory and removes BusinessDirectoryPages entries
    /// </summary>
    private void RemoveBusinessDirectoryEntries()
    {
        try
        {
            // first, remove the BusinessDirectoryPages entries
            BusinessDirectoryPageList businessDirectoryPageList = new BusinessDirectoryPageFactory(neoContext).FindAllObjects();
            foreach (BusinessDirectoryPage businessDirectoryPage in businessDirectoryPageList)
            {
                businessDirectoryPage.Delete();
            }
            neoContext.SaveChanges();
            // now, remove the BusinessDirectory entries
            BusinessDirectoryList businessDirectoryList = new BusinessDirectoryFactory(neoContext).FindAllObjects();
            foreach (BusinessDirectory businessDirectory in businessDirectoryList)
            {
                businessDirectory.Delete();
            }
            neoContext.SaveChanges();
            L_MessageOutput.Text += "<span class='success'>Removed business directory entries successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to remove business directory entries.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to remove business directory entries.</span><br>";
        }
    }

    /// <summary>
    /// Removes the NewsPaper, Ads, Articles, Photos, and Layouts
    /// </summary>
    private void RemoveNewspaper()
    {
        try
        {
            // first, remove the Layout entries
            NewspaperLayoutList newspaperLayoutList = new NewspaperLayoutFactory(neoContext).FindAllObjects();
            foreach (NewspaperLayout newspaperLayout in newspaperLayoutList)
            {
                newspaperLayout.Delete();
            }
            neoContext.SaveChanges();

            // now, remove the Ad Entries
            AdList adList = new AdFactory(neoContext).FindAllObjects();
            foreach (Ad ad in adList)
            {
                ad.Delete();
            }
            neoContext.SaveChanges();

            // now, remove the Article entries
            ArticleList articleList = new ArticleFactory(neoContext).FindAllObjects();
            foreach (Article article in articleList)
            {
                article.Delete();
            }
            neoContext.SaveChanges();

            // now, remove the NewspaperPhoto entries
            NewspaperPhotoList newspaperPhotoList = new NewspaperPhotoFactory(neoContext).FindAllObjects();
            foreach (NewspaperPhoto newspaperPhoto in newspaperPhotoList)
            {
                newspaperPhoto.Delete();
            }
            neoContext.SaveChanges();

            // now, remove the main Newspaper entry
            NewspaperList newspaperList = new NewspaperFactory(neoContext).FindAllObjects();
            foreach (Newspaper newspaper in newspaperList)
            {
                newspaper.Delete();
            }
            neoContext.SaveChanges();
            L_MessageOutput.Text += "<span class='success'>Removed newspaper entries successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to remove newspaper items.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to remove newspaper items.</span><br>";
        }
    }

    /// <summary>
    /// Removes SavedBookmark entries and SavedBookmarkMessage entries
    /// </summary>
    private void RemoveSavedBookmarks()
    {
        try
        {
            // first, remove the SavedBookmarkMessage entries
            SavedBookmarkMessageList savedBookmarkMessageList = new SavedBookmarkMessageFactory(neoContext).FindAllObjects();
            foreach (SavedBookmarkMessage savedBookmarkMessage in savedBookmarkMessageList)
            {
                savedBookmarkMessage.Delete();
            }
            neoContext.SaveChanges();
            // now, remove the SavedBookmark entries
            SavedBookmarkList savedBookmarkList = new SavedBookmarkFactory(neoContext).FindAllObjects();
            foreach (SavedBookmark savedBookmark in savedBookmarkList)
            {
                savedBookmark.Delete();
            }
            neoContext.SaveChanges();
            L_MessageOutput.Text += "<span class='success'>Removed saved bookmarks successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to remove bookmarks.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to remove bookmarks.</span><br>";
        }
    }


    /// <summary>
    /// Removes BusinessWebPages and PersonalWebPages
    /// </summary>
    private void RemoveWebPages()
    {
        try
        {
            // first, remove the PersonalWebPage entries
            PersonalWebPageList personalWebPageList = new PersonalWebPageFactory(neoContext).FindAllObjects();
            foreach (PersonalWebPage personalWebPage in personalWebPageList)
            {
                personalWebPage.Delete();
            }
            neoContext.SaveChanges();
            // now, remove the BusinessWebPage entries
            BusinessWebPageList businessWebPageList = new BusinessWebPageFactory(neoContext).FindAllObjects();
            foreach (BusinessWebPage businessWebPage in businessWebPageList)
            {
                businessWebPage.Delete();
            }
            L_MessageOutput.Text += "<span class='success'>Removed personal and business webpages successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to remove webpages.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to remove webpages.</span><br>";
        }
    }

    /// <summary>
    /// Removes Sign entries
    /// </summary>
    private void RemoveSigns()
    {
        try
        {
            // now, remove the SavedBookmark entries
            SignList signList = new SignFactory(neoContext).FindAllObjects();
            foreach (Sign sign in signList)
            {
                sign.Delete();
            }
            neoContext.SaveChanges();
            L_MessageOutput.Text += "<span class='success'>Removed signs successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to remove signs.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to remove signs.</span><br>";
        }
    }

    private void ResetAutoSavings()
    {
        try
        {
            Autosavings autosavings = new AutosavingsFactory(neoContext).FindUnique("EntryId={0}", 1);
            autosavings.HasBeenTriggered = false;
            neoContext.SaveChanges();
            L_MessageOutput.Text += "<span class='success'>Autosavings was reset successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to reset auto-savings.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to reset auto-savings.</span><br>";
        }
    }


    private void ResetPaycheckDirectDeposit()
    {
        try
        {
            PaycheckDirectDeposit paycheckdirectdeposit = new PaycheckDirectDepositFactory(neoContext).FindUnique("EntryId={0}", 1);
            paycheckdirectdeposit.HasBeenTriggered = false;
            neoContext.SaveChanges();
            L_MessageOutput.Text += "<span class='success'>Direct Deposit was reset successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to reset direct deposit.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to reset direct deposit.</span><br>";
        }
    }


    private void DeleteMediaCenterFiles()
    {
        try
        {
            string rootPath = Server.MapPath("~/");
            FileHelper.DeleteFilesInDirectory(rootPath + "\\media\\ads");
            FileHelper.DeleteFilesInDirectory(rootPath + "\\media\\articles");
            FileHelper.DeleteFilesInDirectory(rootPath + "\\media\\images\\photos");
            FileHelper.DeleteFilesInDirectory(rootPath + "\\media\\web_pages\\business");
            FileHelper.DeleteFilesInDirectory(rootPath + "\\media\\web_pages\\personal");
            string zipFile = rootPath + "\\media\\web_pages\\WebPages.zip";
            if (File.Exists(zipFile))
            {
                File.Delete(zipFile);
            }
            L_MessageOutput.Text += "<span class='success'>Media center files were removed successfully.</span><br>";
        }
        catch (Exception exception)
        {
            SetFailureMessage(L_Message, "An error occurred while attempting to remove media center files.", exception);
            L_MessageOutput.Text += "<span class='warning'>An error while attempting to remove media center files.</span><br>";
        }
    }

}
